/*
** connectToServer.c for  in /home/tessa_b//proj/zappy-2011/client_graphique
** 
** Made by arnaud1 tessa
** Login   <tessa_b@epitech.net>
** 
** Started on  Thu Jun 16 16:14:17 2011 arnaud1 tessa
** Last update Thu Jun 16 19:27:28 2011 el-hadji-malick-ndour dieng
*/

#include	<netdb.h>
#include	<arpa/inet.h>
#include	<netinet/in.h>
#include	<sys/socket.h>
#include	<stdlib.h>
#include	"client.h"

int		connectToServer(t_client *this, char *host, int port)
{
  int			res;
  int			sock;
  int			protocol;
  struct protoent	*pe;
  struct hostent	*he;
  struct in_addr	*addr;
  struct sockaddr_in	sin;

  pe = getprotobyname("tcp");
  if (pe == NULL)
    {
      return (FALSE);
    }
  protocol = pe->p_proto;
  
  sock = socket(PF_INET, SOCK_STREAM, protocol);
  if (sock == -1)
    {
      return (FALSE);
    }
  this->fd = sock;
  
  he = gethostbyname(host);
  if (he == NULL)
    {
      return (FALSE);
    }
  addr = (struct in_addr *) he->h_addr_list[0];

  sin.sin_family = AF_INET;
  sin.sin_port = htons(port);
  sin.sin_addr = *addr;
  
  res = connect(sock, (struct sockaddr *)&sin, sizeof(struct sockaddr_in));
  if (res == -1)
    {
      return (FALSE);
    }
  return (TRUE);
}
